/*********************************************************************\
*         Jamper - Java XML mapper (visual XSLT generator)            *
*                Copyright (C) 2005 Filip Pavlovic                    *
*                    sqba@users.sourceforge.net                       *
*                                                                     *
*  This program is free software; you can redistribute it and/or      *
*  modify it under the terms of the GNU General Public License        *
*  as published by the Free Software Foundation; either version 2     *
*  of the License, or (at your option) any later version.             *
*                                                                     *
*  This program is distributed in the hope that it will be useful,    *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of     *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *
*  GNU General Public License for more details.                       *
*                                                                     *
*  You should have received a copy of the GNU General Public License  *
*  along with this program; if not, write to the Free Software        *
*  Foundation, Inc., 59 Temple Place - Suite 330, Boston,             *
*  MA 02111-1307, USA.                                                *
*                                                                     *
\*********************************************************************/


package sqba.jamper.map.tree.model;


import sqba.jamper.map.tree.MapperTree;
import sqba.jamper.map.tree.MapperTreeNode;
import sqba.jamper.util.PathList;

//import javax.swing.tree.DefaultTreeModel;

//import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
//import java.net.*;
import java.util.Enumeration;
import javax.swing.JOptionPane;
//import javax.swing.tree.*;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.parser.ParserDelegator;
import javax.swing.text.html.HTMLEditorKit;
//import javax.swing.JTree;
import javax.swing.tree.TreePath;


/**
 * Simple HTMLModel document loader class using...
 *
 * @author Filip Pavlovic
 * @version 1.0
 */
public class HTMLTreeModel extends MapperTreeModel
{
	/** Parent node that new entries are added to. */
	private MapperTreeNode	_parent	= null;
	private MapperTreeNode	_root	= null;
//	private Thread		_myThread	= null;
	private MapperTree	_tree		= null;
	private boolean		_bStart		= true;
	private PathList	_path		= new PathList();
	protected String	_uri		= "";

	public HTMLTreeModel(MapperTreeNode newRoot)
	{
		super(newRoot);
		_root	= newRoot;
		_parent	= newRoot;
		_tree	= newRoot.getTree();
	}

	public boolean Load(String uri)
	{
		super._bLoaded = false;
		_uri = uri;
		_bStart = true;

		try {
			BufferedReader reader = new BufferedReader(new FileReader(_uri));
			//System.out.println("Parsing " + _strPath);
			String str = "Parsing ";
			str.concat(_uri);
			System.out.println(str);
			new ParserDelegator().parse(reader, new CallbackHandler(), true);
			// Ako se ne pozove setRoot onda root node ostaje prazan!
			// Ovo je vezano za MapperTreeNode.isLeaf. Da li je ovo bag?
			setRoot((MapperTreeNode)getRoot());
			((MapperTree)HTMLTreeModel.this._tree).expandAll(new TreePath(root), true);
			super._bLoaded = true;
			return true;
		} catch (IOException ioe) {
			//System.out.println("IOE: " + ioe);
			System.out.print("IOE: ");
			System.out.println(ioe);
			JOptionPane.showMessageDialog(null, "Load Bookmarks",
											"Unable to load bookmarks",
											JOptionPane.ERROR_MESSAGE);
		}

		return false;
	}


    //private static final short NO_ENTRY = 0;
    //private static final short BOOKMARK_ENTRY = 2;
    //private static final short DIRECTORY_ENTRY = 3;

	/**
	 * The heart of the parsing. The parser parses the data and notifies
	 * a delegate, via the HTMLEditorKit.ParserCallback interface, as the
	 * data is parsed.
	 */
	private class CallbackHandler extends HTMLEditorKit.ParserCallback
	{
		/**
		* Creates the CallbackHandler.
		*/
		public CallbackHandler()
		{
			//parent = root;
			//lastBookmark = new BookmarkEntry();
		}

		//
		// HTMLEditorKit.ParserCallback methods
		//

		/**
		* Invoked when text in the html document is encountered.
		*/
		public void handleText(char[] data, int pos)
		{
			if(_parent != null)
				_parent.setValue(new String(data));
		}

		/**
		* Invoked when a start tag is encountered.
		*/
		public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos)
		{
			//if(_parent == null)
			//	return;

			if(null == _parent)
				_parent = _root;

			_path.add(t.toString());

			//System.out.println("handleStartTag " + t.toString() + " " + _path);

			MapperTreeNode newNode = new MapperTreeNode(t.toString(), HTMLTreeModel.this._tree);
			newNode.setAllowsChildren(true);

			if (_bStart) {
				setRoot(newNode);
				_bStart = false;
			} else
				_parent.add(newNode);

			_parent = newNode;

			for(Enumeration e = a.getAttributeNames(); e.hasMoreElements(); ) {
				Object o = e.nextElement();
                Object v = a.getAttribute(o);

                String attName = o.toString();
                if(!attName.equals("_implied_")) {
					MapperTreeNode attNode = new MapperTreeNode(attName, HTMLTreeModel.this._tree);

					String val = v.toString();
					if(val.length() > 0)
						attNode.setValue(val);

					attNode.setAllowsChildren(false);
					newNode.add(attNode);
				}
			}

			/*MapperTreeNode attNode;
		    for (int i = 0; i < a.getAttributeCount(); i++) {
		    	//Object att = a.getAttribute(i);
		    	//System.out.println(att);
		    	String attName = a.getLocalName(i);
		    	String val = attrs.getValue(i);
				attNode = new MapperTreeNode(attName, SAXModel.this._tree);
				if(val.length() > 0)
					attNode.setValue(val);
				attNode.setAllowsChildren(false);
				newNode.add(attNode);
		    }*/
		}

		/**
		* Invoked when the end of a tag is encountered.
		*/
		public void handleEndTag(HTML.Tag t, int pos)
		{
			//System.out.println("handleEndTag " + t.toString() + " " + _path);
			//if(_parent == null)
			//	return;

			if(null == _parent)
				_parent = _root;
			else
				_parent = (MapperTreeNode)_parent.getParent();

			if(!t.toString().equals(_path.getLast()))
				System.out.println("Malformed XML document!");

			_path.removeLast();
		}
	}

    public void valueForPathChanged(TreePath path, Object newValue)
    {
		MapperTreeNode node = (MapperTreeNode)path.getLastPathComponent();
		node.setName((String)newValue);
		nodeChanged(node);
    }
}
